package com.akita.spring.ai.controller;

import com.akita.spring.ai.entity.po.School;
import com.akita.spring.ai.enums.BizTypeEnum;
import com.akita.spring.ai.repository.ChatHistoryRepository;
import com.akita.spring.ai.service.ISchoolService;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.model.Media;
import org.springframework.util.MimeType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
    @Resource
    private ChatClient ollamaChatClient;

    @Resource
    private ChatClient aliMultiModalChatClient;

    @Resource
    private ChatHistoryRepository chatHistoryRepository;

    @Resource
    private Executor executorService;

    @Resource
    private ISchoolService iSchoolService;

    @GetMapping(value = "/school")
    public List<School> school() {
        // 测试学校服务
        return iSchoolService.list();
    }


    @RequestMapping(value = "/chat")
    public Void chat() {
        // 并行执行20次,并打印结果,并判断有多少返回结果
        for (int i = 0; i < 20; i++) {
            int finalI = i;
            executorService.execute(() -> {
                String result = textChat("你叫什么名字", "chatId" + finalI);
                log.info("第{}次请求结果：{}", finalI, result);
            });
        }
        return null;
    }

    private String textChat(String prompt,String chatId) {
        return ollamaChatClient.prompt()
                .user(prompt)
                .advisors(advisorSpec -> advisorSpec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .call()
                .content();
    }

    private Flux<String> multiModalChat(String prompt, String chatId,
                                        List<MultipartFile> files) {
        // 解析多媒体文件
        List<Media> mediaList = files.stream()
                .map(file -> new Media(
                        MimeType.valueOf(Objects.requireNonNull(file.getContentType())),
                        file.getResource())
                )
                .toList();

        return aliMultiModalChatClient.prompt()
                .user(p -> p.text(prompt).media(mediaList.toArray(Media[]::new)))
                .advisors(advisorSpec -> advisorSpec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream()
                .content();
    }
}
